package cn.sofwin.day0205;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadTest {
    public static void main(String[] args) throws IOException {
        // read file
        //String content = readFileToString("D:/dev/java/works/java2021/src/cn/sofwin/day0205/test.txt");
        //System.out.println(content);

        //List<String> lines = readFileToString2("D:/dev/java/works/java2021/src/cn/sofwin/day0205/test.txt");
        //lines.forEach(System.out::println);

        // 通过scanner读取文件
        List<String> lines = readFileToString3("D:/dev/java/works/java2021/src/cn/sofwin/day0205/test.txt");
        System.out.println(lines);
    }

    static List<String> readFileToString3(String filePath) throws IOException{
        File file = new File(filePath);
        Scanner sc = new Scanner(System.in);

        List<String> lines = new ArrayList<>();
        while (sc.hasNext()){
            lines.add(sc.next());
        }

        sc.close();
        return lines;
    }

    static String readFileToString(String filePath) throws IOException{
        // create file input stream
        File file = new File(filePath);
        InputStream is = new FileInputStream(file);

        // create storage byte
        byte[] buff = new byte[(int)file.length()];

        // 读取到字节数组
        is.read(buff);

        // close inputstream
        is.close();

        // 根据字节数组创建字符串
        return  new String(buff);
    }

    static List<String> readFileToString2(String filePath) throws IOException{
        //
        File file = new File(filePath);
        BufferedReader br = new BufferedReader(new FileReader(file));

        // 读取文件内容
        List<String> lines = new ArrayList<>();
        String line = null;
        while ( (line = br.readLine()) != null ){
            lines.add(line);
        }

        br.close();

        return lines;
    }
}
